package com.personal.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.personal.pojo.*;
import com.personal.service.*;
import com.personal.utils.GetAWeekCourse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/member")
public class MemberController {

    //设置每页显示数据量
    private static final int PAGE_SIZE = 10;
    @Autowired
    private MemberService memberService;

//1.登录
    @RequestMapping("/login")
    @ResponseBody
    public String login(String username, String password, HttpSession session){
        TMember member = memberService.login(username,password);
//        System.out.println(member);
        if (member!=null){
            //将登录用户信息存入session
            session.setAttribute("logUsername",member.getMemrealname());
            session.setAttribute("logUser",member);
            return "ok_me";
        }else{
            return "no";
        }
    }

    //1.1登录信息验证成功跳转页面
    @RequestMapping("/toIndex")
    public String toIndex(){

        return "index";
    }

//2.退出登录,移除会话
    @RequestMapping("/outlogin")
    public String outlogin(HttpSession session){
        //移除登录会话信息
        session.removeAttribute("logUser");
        //销毁所有会话内容
        session.invalidate();
        return "login";
    }

//3.注册
    @RequestMapping("/register")
    public String register(TMember member){
        int row = memberService.register(member);
        return "registers";
    }
    //3.1注册名不能重复
    @RequestMapping("/checkName")
    @ResponseBody//此处不能省略，不然Ajax无法接受返回值
    public String checkName(String username){
        List list = memberService.findByName(username);
        if (list.size()==0){
            return "ok";
        }else {
            return "no";
        }
    }

//4 跳转到个人中心页面
    @RequestMapping("/toOneselfpage")
    public String toOneselfpage(){

        return "memOneself";
    }

    //4.1修改登录用户个人信息（编辑）
    @RequestMapping("/memedit")
    @ResponseBody
    public String edit(String memid,String memlogname,String mempassword,String memrealname,String memsex,HttpSession session){
        TMember member = new TMember();
        member.setMemid(Integer.valueOf(memid));
        member.setMemlogname(memlogname);
        member.setMemrealname(memrealname);
        member.setMempassword(mempassword);
        member.setMemsex(memsex);
        //修改信息
        int row = memberService.editByKey(member);
        System.out.println(row);
        //修改成功则更新session内容
        if (row==1){
            TMember newMember = memberService.selectByKey(Integer.valueOf(memid));
            session.setAttribute("logUser",newMember);
            return "ok";
        }else {
            return "no";
        }
    }

    //4.2个人中心：获取登录用户报的所有课程,根据用户id来查
    @RequestMapping("/getAllCourse")
    @ResponseBody
    public String getAllCourse(String memid){
        if (!memid.isEmpty()){
            List list = memberService.findAllcourse(Integer.valueOf(memid));
            //如果非空则转为JSON传递给前端
            if (list.size()!=0){
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    String json = objectMapper.writeValueAsString(list);
                    return json;
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //4.2个人中心：获取登录用户预约的所有教练,根据用户id来查
    @RequestMapping("/getAllCoach")
    @ResponseBody
    public String getAllCoach(String memid){
        //1.查询用户教练预约情况，从reserve表中查
        List list = memberService.findAllCoach(Integer.valueOf(memid));
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(list);
            return json;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 4.3跳转到登录用户个人 课程表 页面
    @RequestMapping("/toMemcourseSchedule")
    public String toMemcourseSchedule(Model model,HttpSession session){
        //获取session内容，也就是登录的用户信息
        TMember member = (TMember) session.getAttribute("logUser");
        //1.从报名表获取用户所有报名的课程（未结束的课程）
        List<TApply> list = memberService.findAllcourseNoEnd(member.getMemid());

        //遍历将报名表中的课程信息，赋予相应的位置str=a11：代表第一节 星期一。
        list.forEach(apply -> {
            //获取报名表中的课程
            TCourse course = apply.getCourse();
            //获取星期几
            String strWeek = String.valueOf(apply.getCourse().getWeek().getWeekid());
            //获取第几节课
            String strSection = String.valueOf(apply.getCourse().getSection().getSectionid());
            //第几节+第几周
            String str ="a"+strSection+strWeek;
            model.addAttribute(str,course);
        });
        return "memcourse_schedule";
    }

//5 跳转coach列表，分页显示coach
    @RequestMapping("/toCoachpage")
    public String splitOnepage(Model model){
        PageInfo info = memberService.splitCoach(1,PAGE_SIZE);
        model.addAttribute("coachInfo",info);
        return "memcoach_list";
    }
    //5.1 全部信息分页跳转ajax
    @RequestMapping("/coachPageSplit")
    @ResponseBody
    public void coachPageSplit(int page, HttpSession session){
        //取得当前page参数页面数据
        PageInfo info = memberService.splitCoach(page,PAGE_SIZE);
        session.setAttribute("coachInfo",info);
    }
    //5.2 多条件查询（会员用户 教练模块功能）,分页显示
    @RequestMapping("/memfindcoach")
    @ResponseBody
    public void selectBycluse(String cotype,String username,HttpSession session){
        PageInfo info = memberService.memFineCoach(1,PAGE_SIZE,cotype,username);
        session.setAttribute("coachInfo",info);
    }
    //5.3 多条件查询分页（会员用户 教练模块功能）,带条件分页跳转
    @RequestMapping("/selectSplit")
    @ResponseBody
    public void selectSplit(int page,String cotype,String username,HttpSession session){
        PageInfo info = memberService.memFineCoach(page,PAGE_SIZE,cotype,username);
        session.setAttribute("coachInfo",info);
    }
    //5.4 教练预约
    @RequestMapping("/reserveCoach")
    @ResponseBody
    public String reserveCoach(Integer coachid,HttpSession session){
        //判断是否重复预约
        TMember member = (TMember) session.getAttribute("logUser");
        TReserve reserve1 = memberService.findByMemCoa(member.getMemid(),coachid);
        if (reserve1==null){
            // 为空则没有预约
            TCoach coach = memberService.findBycoachId(coachid);
            //根据教练号查询教练，存入session中，让确认预约页面展示
            session.setAttribute("reserveCoach",coach);
            return "ok";
        }
        return "no";
    }
    //5.5 确认预约，插入预约表中
    @RequestMapping("/reserveConfim")
    @ResponseBody
    public String reserveConfim(Integer resermem,Integer resercoach,HttpSession session){
        //移除预约需要的session
        session.removeAttribute("reserveCoach");
        //防止重复点击预约按钮,再次判断是否已经插入
        TReserve reserve1 = memberService.findByMemCoa(resermem,resercoach);
        if (reserve1==null){
            //调用插入方法
            int row = memberService.addReserve(resermem,resercoach);
            return "ok";
        }else {
            return "no";
        }
    }
    //5.6 日期修改
    @RequestMapping("/changeDate")
    @ResponseBody
    public String changeDate(String reserveid,HttpSession session){
        //根据id，查询reserve
        TReserve reserve = memberService.findByResId(Integer.valueOf(reserveid));
        if (reserve!=null){
            session.setAttribute("reserve",reserve);
            return "ok";
        }
        return "no";
    }

    //5.7 修改时间，会员与教练约好时间就自己修改
    @RequestMapping("/changeDates")
    @ResponseBody
    public String changeDates(String reserveid,String reservedate){
        //修改相应reserve表的时间
//        System.out.println(reservedate);
        TReserve reserve = new TReserve();
        reserve.setReserveid(Integer.valueOf(reserveid));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date resdate = sdf.parse(reservedate);
            reserve.setReservedate(resdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int row = memberService.editDate(reserve);
        if (row==1){
            return "ok";
        }
        return "no";
    }
//6 跳转到课程页面,分页显示
    @RequestMapping("/toCoursepage")
    public String toCoursepage(HttpSession session){
        PageInfo info = memberService.findAllCourse1(1,PAGE_SIZE);
        session.setAttribute("courseInfo",info);
        return "memcourse_list";
    }
    //6.1 分页跳转ajax
    @RequestMapping("/ajaxsplit2")
    @ResponseBody
    public void ajaxPage2(int page, HttpSession session){
        //取得当前page参数页面数据
        System.out.println(page);
        PageInfo info = memberService.findAllCourse1(page,PAGE_SIZE);
        session.setAttribute("courseInfo",info);
    }
    //6.2多条件查询课程信息,分页显示
    @ResponseBody
    @RequestMapping("/memfindcourse")
    public void findMoreCluse(Float minMoney, Float maxMoney, String coursename,HttpSession session){
        PageInfo info = memberService.findByClause(1,PAGE_SIZE,minMoney,maxMoney,coursename);
        session.setAttribute("courseInfo",info);
    }
    //6.3多条件查询课程信息，分页跳转
    @ResponseBody
    @RequestMapping("/findSplit")
    public void findSplit(int page,Float minMoney, Float maxMoney, String coursename,HttpSession session){
        PageInfo info = memberService.findByClause(page,PAGE_SIZE,minMoney,maxMoney,coursename);
        session.setAttribute("courseInfo",info);
    }
    //6.4 判断是否报名满人
    @RequestMapping("/countMem")
    @ResponseBody
    public String countMem(Integer courseid){
        //根据id查询课程,获取课程最大报名人数
        TCourse course = memberService.findBycourseId(courseid);
        //获取本课程已经报名人数
        int applyMem = memberService.countMem(courseid);
        if (applyMem+1 <= course.getCourseMem()){
            //未报满人
            return "ok";
        }else {
            return "no";
        }
    }
    //6.5跳转确认课程报名页面
    @RequestMapping("/confirmation")
    @ResponseBody
    public String confirmation(Integer courseid,HttpSession session){
        //判断是否报名
        TMember member = (TMember) session.getAttribute("logUser");
        TApply apply = memberService.findByMemCourse(member.getMemid(),courseid);
        if (apply==null){
            //根据id查询课程,来展示报名信息
            TCourse course = memberService.findBycourseId(courseid);
            //将课程信息存入session，方便确认信息页面能获取到
            session.setAttribute("applyCourse",course);
            return "ok";
        }else {
            return "no";
        }
    }
    //6.6确认报名，将报名信息写入报名表
    @RequestMapping("/applyCourse")
    @ResponseBody
    public String applyCourse(Integer applymem,Integer applycourse,HttpSession session){
        //移除报名需要的session
        session.removeAttribute("applyCourse");
        //1.首先得确认是否已报名，避免重复报名。
        TApply apply = memberService.findByMemCourse(applymem,applycourse);
        if (apply == null){
            //插入报名表
            int row = memberService.addApply(applymem,applycourse);
            return "ok";
        }else {
            return "no";
        }
    }

}
